package cn.yunhe.dao.impl;

import cn.yunhe.dao.TypeDao;
import cn.yunhe.model.Type;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

/*spring注解*/
@Repository(value = "typeDao")
public class TypeDaoImpl extends HibernateDaoSupport implements TypeDao {

    @Autowired
    @Qualifier("sessionFactory")
    public void setSessionFactory111(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }


    @Override
    public boolean insertType(Type type) {
        getHibernateTemplate().save(type);
        return false;
    }

    @Override
    public boolean updateType(Type type) {
        getHibernateTemplate().update(type);
        return false;
    }

    @Override
    public boolean deleteType(Integer sid) {
        getHibernateTemplate().delete(this.getById(sid));
        return false;
    }

    @Override
    public Type getById(Integer sid) {
        Type type=getHibernateTemplate().get(Type.class,sid);
        return null;
    }

    @Override
    public List<Type> searchType(String hql) {
        List<Type>typeList=getHibernateTemplate().find(hql);
        return typeList;
    }

    @Override
    public List<Type> searchType(final Type type) {
        List<Type>typeList=getHibernateTemplate().executeFind(new HibernateCallback<List<Type>>() {
            @Override
            public List<Type> doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria=session.createCriteria(Type.class);

                if (type!=null){
                    if (type.getTid()>0){
                        criteria.add(Restrictions.eq("sid",type.getTid()));
                    }
                    if (type.getTname()!=null&&type.getTname().trim().length()>0){
                        criteria.add(Restrictions.like("sname",type.getTname(),MatchMode.ANYWHERE));
                    }
                }

                List<Type>typeList1=criteria.list();
                return typeList1;
            }
        });
        return null;
    }
}
